package com.yanyilu.basing.service.impl;

import com.yanyilu.basing.common.R;
import com.yanyilu.basing.entity.TotalTimeMileage;
import com.yanyilu.basing.entity.User;
import com.yanyilu.basing.entity.dto.TotalTimeMileDTO;
import com.yanyilu.basing.entity.dto.UserDTO;
import com.yanyilu.basing.mapper.TotalTimeMileageMapper;
import com.yanyilu.basing.mapper.UserMapper;
import com.yanyilu.basing.service.ILeaderboardService;
import com.yanyilu.basing.service.ITotalTimeMileageService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Sxx
 * @since 2020-10-26
 */
@Service
public class TotalTimeMileageServiceImpl extends ServiceImpl<TotalTimeMileageMapper, TotalTimeMileage> implements ITotalTimeMileageService {
    @Autowired
    TotalTimeMileageMapper totalTimeMileageMapper;
    @Autowired
    UserMapper userMapper;

    @Autowired
    ILeaderboardService iLeaderboardService;



    @Override
    public R getTatalTimeMileage(Integer userId) {
        TotalTimeMileDTO totalTimeMileDTO = totalTimeMileageMapper.selectDTOByUserId(userId);

        return R.ok().put("totalTimeMileDTO", totalTimeMileDTO);
    }
    /**
     * 获取排名信息
     * @param userId
     * @return
     */
    @Override
    public R getRankInfo(Integer userId) {
        UserDTO userDTO = totalTimeMileageMapper.getRankByUserId(userId);
        //System.out.println("rank==="+userDTO.getRank());
        if(null == userDTO.getRank()){
            userDTO.setRank(0);
        }
        return R.ok().put("rank",userDTO);
    }

    @Override
    public void addNumber(Integer time, Integer mileage,Integer userId) {
        TotalTimeMileage totalTimeMileage = totalTimeMileageMapper.selectByUserId(userId);
        if(null!=totalTimeMileage){
            totalTimeMileage.setTotalTime(totalTimeMileage.getTotalTime()+time);
            totalTimeMileage.setTotalMileage(totalTimeMileage.getTotalMileage()+mileage);
            totalTimeMileageMapper.updateById(totalTimeMileage);
            iLeaderboardService.adminAdd(totalTimeMileage);
        }else {
            User user = userMapper.selectById(userId);

            TotalTimeMileage totalTimeMileage1 = new TotalTimeMileage();
            totalTimeMileage1.setTotalTime(time);
            totalTimeMileage1.setTotalMileage(mileage);
            totalTimeMileage1.setUserId(userId);
            totalTimeMileage1.setUserName(user.getUserName());
            totalTimeMileage1.setHeadImage(user.getHeadImge());

            totalTimeMileageMapper.insert(totalTimeMileage1);
            iLeaderboardService.adminAdd(totalTimeMileage1);
        }

    }

}
